from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from after.models import ReturnFrom, ReissuePB, ReturnDevice
from trade.models import Agent
from after.utils import getStrTime, getTag, getDevices

import time
import json


class ReturnAPIView(APIView):
    """退换货表单提交"""

    def post(self, request):
        resp = {'code': 200, 'msg': '退换货提交成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        customer_id = req['customerId'] if 'customerId' in req else ''
        customer_name = req['customerName'] if 'customerName' in req else ''
        phone = req['phone'] if 'phone' in req else ''
        receipt_num = req['receiptNum'] if 'receiptNum' in req else ''
        address = req['address'] if 'address' in req else ''
        date = req['date'] if 'date' in req else getStrTime()
        reason = req['reason'] if 'reason' in req else ''
        return_type = req['returnType'] if 'returnType' in req else 0
        bs_type = req['bsType'] if 'bsType' in req else 0
        goods = req['goods'] if 'goods' in req else ''

        try:
            agent = Agent.objects.get(customer_id=customer_id, status=1)
        except:
            agent = Agent.objects.create(customer_id=customer_id, customer_name=customer_name, mobile=phone,
                                         type=int(bs_type))

        try:
            if bs_type == 0:
                return_num = 'JS' + str(int(time.time()))
            else:
                return_num = 'QD' + str(int(time.time()))
            return_from = ReturnFrom.objects.create(customer=agent, receipt_num=receipt_num, address=address,
                                                    return_num=return_num,
                                                    date=date, bs_type=int(bs_type), return_type=int(return_type),
                                                    reason=reason)

            if isinstance(goods, list):
                for good in goods:
                    try:
                        ReturnDevice.objects.create(device=good['device'], count=good['count'], return_from=return_from)
                    except:
                        resp['code'] = 400
                        resp['msg'] = '设备单创建失败'
                        resp['success'] = False
                        return Response(resp, status=status.HTTP_400_BAD_REQUEST)
                resp['data'] = {"return_num": return_from.return_num}
            else:
                resp['code'] = 400
                resp['msg'] = 'goods参数错误，非法参数'
                resp['success'] = False
                return Response(resp, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            resp['code'] = 400
            resp['msg'] = '退货单创建失败'
            resp['success'] = False
            return Response(resp, status=status.HTTP_400_BAD_REQUEST)

        return Response(resp, status=status.HTTP_200_OK)


class ReissueAPIView(APIView):
    """补宝表单提交"""

    def post(self, request):
        resp = {'code': 200, 'msg': '补宝提交成功！', 'data': {}, 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        customer_id = req['customerId'] if 'customerId' in req else ''
        customer_name = req['customerName'] if 'customerName' in req else ''
        phone = req['phone'] if 'phone' in req else ''
        address = req['address'] if 'address' in req else ''
        date = req['date'] if 'date' in req else getStrTime()
        bs_type = req['bsType'] if 'bsType' in req else 0
        count = req['count'] if 'count' in req else ''
        try:
            agent = Agent.objects.get(customer_id=customer_id, status=1)
        except:
            agent = Agent.objects.create(customer_id=customer_id, customer_name=customer_name, mobile=phone,
                                         type=int(bs_type))

        try:
            reissue_num = 'PB' + str(int(time.time()))

            reissue = ReissuePB.objects.create(reissue_num=reissue_num, customer=agent, count=count,
                                               address=address, date=date, bs_type=int(bs_type))

            resp['data'] = {"reissue_num": reissue.reissue_num}
        except Exception as e:
            resp['code'] = 400
            resp['msg'] = '补宝单创建失败'
            resp['success'] = False
            return Response(resp, status=status.HTTP_400_BAD_REQUEST)
        return Response(resp)


# after/query
class QueryAPIView(APIView):
    """售后查询"""

    def post(self, request):
        resp = {'code': 200, 'msg': '查询成功！', 'success': True, 'timestamp': int(time.time())}
        req = json.loads(request.body)
        order_num = req['orderNum'] if 'orderNum' in req else ''

        # 提取标签
        tag = order_num[:2]
        print(tag)
        if tag == 'JS' or tag == 'QD':
            try:
                info = ReturnFrom.objects.get(return_num=order_num, status=1)
                devices = getDevices(info)
                data = {
                    'id': info.return_id,
                    'return_num': info.return_num,
                    'receipt_num': info.receipt_num,
                    'return_type': getTag(info.return_type, 2),
                    'bs_type': getTag(info.bs_type, 3),
                    'date': info.date,
                    'address': info.address,
                    'review_status': getTag(info.review_status, 0),
                    'delivery_status': getTag(info.delivery_status, 1),
                    'reason': info.reason,
                    'devices': devices
                }
                if info.delivery_status == 1:
                    data['delivery_num'] = info.delivery_num
            except Exception as e:
                print(e)
                resp['code'] = 400
                resp['msg'] = '查询无该退换货订单号信息'
                resp['success'] = False
                return Response(resp, status=status.HTTP_400_BAD_REQUEST)
        elif tag == 'PB':
            try:
                info = ReissuePB.objects.get(reissue_num=order_num, status=1)
                data = {
                    'id': info.reissue_id,
                    'count': info.count,
                    'date': info.date,
                    'address': info.address,
                    'delivery_num': info.delivery_num,
                    'bs_type': getTag(info.bs_type, 3),
                    'review_status': getTag(info.review_status, 0),
                    'delivery_status': getTag(info.delivery_status, 1),
                }
                if info.delivery_status == 1:
                    data['delivery_num'] = info.delivery_num
            except Exception as e:
                print(e)
                resp['code'] = 400
                resp['msg'] = '查询无该补宝订单号信息'
                resp['success'] = False
                return Response(resp, status=status.HTTP_400_BAD_REQUEST)
        else:
            resp['code'] = 400
            resp['msg'] = '订单号错误'
            resp['success'] = False
            return Response(resp, status=status.HTTP_400_BAD_REQUEST)

        resp['data'] = data
        return Response(resp)
